package sequence;

/**
 * 最长公共子序列 O(N)
 */
public class Main {
    public int LCS (String s1, String s2) {
        // write code here
        // 动态规划
        // dp[i][j] 表示以s1的i位置结尾和s2以j位置结尾的最长公共子序列长度
        int maxLen = 0;
        int start = 0;
        // 创建 dp 表，并初始化为 0
        int[][] dp = new int[s1.length()+1][s2.length()+1];
        for (int i = 0; i < s1.length(); i++) {
            for (int j = 0; j < s2.length(); j++) {
                if (s1.charAt(i) == s2.charAt(j)) {
                    dp[i+1][j+1] = dp[i][j] + 1;
                } else {
                    dp[i+1][j+1] = Math.max(dp[i+1][j],dp[i][j+1]);
                }
            }
        }
        return dp[s1.length()][s2.length()];
    }
}
